package com.xiaozhaovip.demo.controller.util;

import org.apache.commons.lang.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 正则工具类
 *
 * @author Cauli
 */
public class PatternUtils {
    /**
     * 判断文本中是否有手机号
     *
     * @param content
     * @return
     */
    public static boolean isPhoneNumber(String content) {
        Matcher matcher = getMatcher(content);
        while (matcher.find()) {
            return true;
        }
        return false;
    }

    /**
     * 隐藏文本中的手机号
     *
     * @param content
     * @return
     */
    public static String hidePhoneNumber(String content) {
        Matcher matcher = getMatcher(content);
        while (matcher.find()) {
            content = content.replace(matcher.group(), matcher.group().substring(0, 3) + "********");
        }
        return content;
    }

    private static Matcher getMatcher(String content) {
        if (StringUtils.isBlank(content)) {
            return null;
        }
        final String p = "(?<!\\d)(?:(?:1[3-8]\\d{9})|861[3-8]\\d{9})(?!\\d)";
        Pattern pattern = Pattern.compile(p);
        return pattern.matcher(content);
    }
}
